package com.lawyer.service;

import java.io.InputStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.lawyer.config.QiniuConfigBean;
import com.lawyer.model.Message;
import com.lawyer.model.MessageConstant;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

@Service
public class FileUpLoadService {

	@Autowired
	QiniuConfigBean qiniuConfigBean;

	public Message Upload(MultipartFile file) {
		Message msg = new Message();
		// 普通上传
		Configuration cfg = new Configuration(Region.region0());
		UploadManager uploadManager = new UploadManager(cfg);
		// 生成上传凭证，然后准备上传
		String accessKey = qiniuConfigBean.getAccessKey();
		String secretKey = qiniuConfigBean.getSecretKey();
		String bucket = qiniuConfigBean.getBucket();
		// 默认不指定key的情况下，以文件内容的hash值作为文件名
		String key = null;
		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(bucket);
		try {
			Response response = uploadManager.put(file.getBytes(), key, upToken);
			// 解析上传成功的结果
			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			String url = qiniuConfigBean.getShowUrl() + putRet.hash;
			msg.setCode(MessageConstant.SUCCESS_CODE);
			msg.setData(url);
			msg.setMessage(MessageConstant.SUCCESS_MSG);
		} catch (Exception e) {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(e.getMessage());
		}

		return msg;

	}
	
	public Message Upload(InputStream input) {
		Message msg = new Message();
		// 普通上传
		Configuration cfg = new Configuration(Region.region0());
		UploadManager uploadManager = new UploadManager(cfg);
		// 生成上传凭证，然后准备上传
		String accessKey = qiniuConfigBean.getAccessKey();
		String secretKey = qiniuConfigBean.getSecretKey();
		String bucket = qiniuConfigBean.getBucket();
		// 默认不指定key的情况下，以文件内容的hash值作为文件名
		String key = null;
		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(bucket);
		try {
			Response response = uploadManager.put(input, key, upToken,null,null);
			// 解析上传成功的结果
			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			String url = qiniuConfigBean.getShowUrl() + putRet.hash;
			msg.setCode(MessageConstant.SUCCESS_CODE);
			msg.setData(url);
			msg.setMessage(MessageConstant.SUCCESS_MSG);
		} catch (Exception e) {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(e.getMessage());
		}

		return msg;

	}

}